package design.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.Connection;

/**
 * java实现动态代理。
 *
 *
 *
 * @author yuqi<307530884@qq.com> <2017/3/23>
 * @version 1.0
 * @since 1.0
 */
public class ConnectionProxyHandler implements InvocationHandler {

	private Connection connection;

    public ConnectionProxyHandler(Connection connection) {
        this.connection = connection;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        //proxy.getClass().isAssignableFrom(Connection.class)用于判断代理类是否实现了Connection接口
        //反例查看 design.proxy.SameMethodClass
        if(proxy.getClass().isAssignableFrom(Connection.class) && "close".equals(method.getName())){
            //return connection to dataSource
        	connection.close();
            return null;
        }

        return null;
    }

    public Connection getProxy(){
        return (Connection) Proxy.newProxyInstance(getClass().getClassLoader(), new Class<?>[]{Connection.class}, this);
    }

}
